package us.kg.kotoriforest.schedule.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import us.kg.kotoriforest.schedule.pojo.SysUser;

import java.io.IOException;

/**
 * 登陆过滤器。用来保护一些需要登录才能访问的资源
 *
 * @author Kotori rotroutine@163.com
 * @since 2024/12/11
 */
@WebFilter({"/schedule/*", "/showSchedule.html"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 参数父转子
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获得session对象
        HttpSession session = request.getSession();
        // 获得session中已登录的用户对象
        SysUser sysUser = (SysUser) session.getAttribute("sysUser");
        // 如果用户对象为空（不存在）则重定向到登录页面；如果存在则放行
        if (sysUser == null) {
            // 没登录过
            response.sendRedirect("/login.html");
        } else {
            // 登录过了
            filterChain.doFilter(request, response);
        }
    }
}
